package com.safety51.bi.service;

import com.safety51.bi.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class NumberMetricService {

    private final ChartConfigService chartConfigService;
    private final DataQueryService dataQueryService;

    public NumberMetricService(ChartConfigService chartConfigService, DataQueryService dataQueryService) {
        this.chartConfigService = chartConfigService;
        this.dataQueryService = dataQueryService;
    }

    public ApiResponse<NumberMetricData> getNumberMetric(ChartDataRequest request) {
        try {
            log.info("开始获取数值指标: {}", request.getChartId());

            ChartConfig config = chartConfigService.getConfigByChartId(request.getChartId());
            if (config == null) {
                log.error("图表配置不存在: {}", request.getChartId());
                return ApiResponse.error("图表配置不存在: " + request.getChartId());
            }

            log.info("找到图表配置: {}, 数据源: {}", config.getChartName(), config.getDataSource());
            log.info("前端过滤条件: {}", request.getFilters());

            List<Map<String, Object>> data = dataQueryService.executeQuery(config, request.getFilters(),
                    request.getPage(),
                    request.getPageSize());
            log.info("查询结果数据条数: {}", data.size());

            NumberMetricData metricData = buildNumberMetricData(config, data);

            return ApiResponse.success(metricData);
        } catch (Exception e) {
            log.error("获取数值指标失败 - ChartId: {}, Error: {}", request.getChartId(), e.getMessage(), e);
            return ApiResponse.error("获取数值指标失败: " + e.getMessage());
        }
    }

    public ApiResponse<Map<String, NumberMetricData>> getBatchNumberMetrics(List<String> chartIds, Map<String, Object> filters) {
        try {
            Map<String, NumberMetricData> result = new HashMap<>();

            for (String chartId : chartIds) {
                ChartConfig config = chartConfigService.getConfigByChartId(chartId);
                if (config != null) {
                    List<Map<String, Object>> data = dataQueryService.executeQuery(config, filters, 0, 10);
                    result.put(chartId, buildNumberMetricData(config, data));
                }
            }

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("批量获取指标失败: " + e.getMessage());
        }
    }

    private NumberMetricData buildNumberMetricData(ChartConfig config, List<Map<String, Object>> data) {
        NumberMetricData metricData = new NumberMetricData();
        metricData.setTitle(config.getChartName());

        Object currentValue = extractCurrentValue(config, data);
        metricData.setValue(currentValue);
        metricData.setFormattedValue(formatValue(currentValue, config.getNumberFormat()));
        metricData.setUnit(extractUnit(config));

        // 对比信息（简化实现）
        if (config.getCompareConfig() != null) {
            CompareInfo compareInfo = calculateCompareInfo(config, data, currentValue);
            metricData.setCompare(compareInfo);
        }

        // 趋势信息
        TrendInfo trendInfo = calculateTrendInfo(config, data);
        metricData.setTrend(trendInfo);

        return metricData;
    }

    private Object extractCurrentValue(ChartConfig config, List<Map<String, Object>> data) {
        if (data == null || data.isEmpty()) {
            return 0;
        }

        Map<String, Object> firstRow = data.get(0);

        if (config.getMetrics() != null && !config.getMetrics().isEmpty()) {
            String metricAlias = config.getMetrics().get(0).getAlias();
            return firstRow.get(metricAlias);
        }

        // 返回第一个数值列
        for (Map.Entry<String, Object> entry : firstRow.entrySet()) {
            if (entry.getValue() instanceof Number) {
                return entry.getValue();
            }
        }

        return firstRow.values().iterator().next();
    }

    private String formatValue(Object value, String format) {
        if (value == null) return "0";
        if (format == null) return value.toString();

        try {
            if (value instanceof Number) {
                DecimalFormat formatter = new DecimalFormat(format);
                return formatter.format(value);
            }
        } catch (Exception e) {
            // 格式化失败
        }

        return value.toString();
    }

    private String extractUnit(ChartConfig config) {
        String name = config.getChartName();
        if (name.contains("金额") || name.contains("元")) return "元";
        if (name.contains("百分比") || name.contains("%")) return "%";
        if (name.contains("人数")) return "人";
        if (name.contains("次数")) return "次";
        return "";
    }

    private CompareInfo calculateCompareInfo(ChartConfig config, List<Map<String, Object>> data, Object currentValue) {
        CompareInfo compareInfo = new CompareInfo();

        // 简化实现：假设对比值为当前值的90%
        if (currentValue instanceof Number) {
            double current = ((Number) currentValue).doubleValue();
            double compareValue = current * 0.9;

            compareInfo.setCompareValue(compareValue);
            compareInfo.setFormattedCompareValue(formatValue(compareValue, config.getNumberFormat()));

            double changeRate = (current - compareValue) / compareValue * 100;
            compareInfo.setChangeRate(changeRate);

            if (changeRate > 0) {
                compareInfo.setChangeType("increase");
            } else if (changeRate < 0) {
                compareInfo.setChangeType("decrease");
            } else {
                compareInfo.setChangeType("equal");
            }
        }

        return compareInfo;
    }

    private TrendInfo calculateTrendInfo(ChartConfig config, List<Map<String, Object>> data) {
        TrendInfo trendInfo = new TrendInfo();

        if (data != null && data.size() > 1) {
            // 简化趋势计算
            trendInfo.setTrend("up");
            trendInfo.setTrendDescription("较上期上升");
        } else {
            trendInfo.setTrend("stable");
            trendInfo.setTrendDescription("数据稳定");
        }

        return trendInfo;
    }
}